//
//  HJDTimeWeekViewController.m
//  JYHospital
//
//  Created by 胡金东 on 16/6/18.
//  Copyright © 2016年 胡金东. All rights reserved.
//

#import "HJDTimeWeekViewController.h"
#import "HJDDatePickerView.h"
#import "AFNetworking.h"

@interface HJDTimeWeekViewController ()<UWDatePickerViewDelegate>
{
     HJDDatePickerView * _pickerView;
}

@property (nonatomic,strong) UIButton *timeBtn;

@property (nonatomic,strong) UILabel *timeLbl;

@property (nonatomic,strong) NSString * date;
@property (nonatomic,strong) NSCalendar *cal;
@property (nonatomic,assign) NSInteger flags;
//预产期
@property (nonatomic,strong) UILabel *lblTime ;


@end

@implementation HJDTimeWeekViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"孕产期";
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:19],
       NSForegroundColorAttributeName:[UIColor getColorWithHexNumber:@"848484"]}];
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setTitle:@"保存" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor getColorWithHexNumber:@"5CC6AB"] forState:UIControlStateNormal];
    [rightBtn sizeToFit];
    [rightBtn addTarget:self action:@selector(saveTimeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    [self setUpContent];
    //添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    tap.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tap];
    
}

//隐藏键盘
-(void)viewTapped:(UITapGestureRecognizer*)tap
{
    
    [self.view endEditing:YES];
    
}



-(void)setUpContent
{
    
    CGFloat lblX = 0 ;
    CGFloat lblY = HJDNavigHeight;
    CGFloat lblW = HJDWidth;
    CGFloat lblH = 40;
    UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(lblX, lblY, lblW, lblH)];
    lbl.backgroundColor = [UIColor getColorWithHexNumber:@"CFCFCF"];
    lbl.text = @"请填写以下内容，我们将为您自动计算宝宝的出生时间";
    lbl.font = [UIFont systemFontOfSize:14];
    lbl.textColor = [UIColor lightGrayColor];
    [self.view addSubview:lbl];

    CGFloat timeBtnX = HJDHorizontalMargin/2 - 3;
    CGFloat timeBtnY = CGRectGetMaxY(lbl.frame) + 10;
    CGFloat timeBtnW = HJDWidth;
    CGFloat timeBtnH = 40;
    self.timeBtn = [[UIButton alloc]initWithFrame:CGRectMake(timeBtnX, timeBtnY, timeBtnW, timeBtnH)];
    [self.timeBtn addTarget:self action:@selector(timeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.timeBtn setTitle:@"末次经期" forState:UIControlStateNormal];
    [self.timeBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, HJDWidth - 80)];
    [self.timeBtn setTitleColor:[UIColor getColorWithHexNumber:@"323232"] forState:UIControlStateNormal];
    [self.view addSubview:self.timeBtn];

    CGFloat timeLblX = HJDWidth - 100 - 20 ;
    CGFloat timeLblY = timeBtnY;
    CGFloat timeLblW = 100;
    CGFloat timeLblH = 40;
    NSUserDefaults *defaP = [NSUserDefaults standardUserDefaults];
    NSString *pre = [defaP objectForKey:@"pregnanc"];
//    末次月经
    self.timeLbl = [[UILabel alloc]initWithFrame:CGRectMake(timeLblX, timeLblY, timeLblW, timeLblH)];
    self.timeLbl.text = pre;
    self.timeLbl.textColor = [UIColor getColorWithHexNumber:@"FE93A2"];
    [self.view addSubview:self.timeLbl];
    
    UIImageView *timeimage = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.timeLbl.frame), timeBtnY + 11, 9, 35/2)];
    timeimage.image = [UIImage imageNamed:@"间号"];
    [self.view addSubview: timeimage];
    
    //    横线
    CGFloat timeviewX = 0 ;
    CGFloat timeviewY = CGRectGetMaxY(self.timeBtn.frame);
    CGFloat timeviewW = HJDWidth ;
    CGFloat timeviewH = 1;
    UIView *timeview = [[UIView alloc]initWithFrame:CGRectMake(timeviewX, timeviewY, timeviewW, timeviewH)];
    timeview.backgroundColor = [UIColor getColorWithHexNumber:@"CFCFCF"];
    [self.view addSubview:timeview];

    
    CGFloat dayX = HJDHorizontalMargin/2 ;
    CGFloat dayY = CGRectGetMaxY(timeview.frame)+5;
    CGFloat dayW = 80;
    CGFloat dayH = 40;

    UILabel *dayLbl = [[UILabel alloc]initWithFrame:CGRectMake(dayX, dayY, dayW, dayH )];
    dayLbl.text = @"经期天数";
    dayLbl.textColor = [UIColor getColorWithHexNumber:@"323232"];
    [self.view addSubview:dayLbl];
    
    CGFloat dayCX = HJDWidth - 80;
    CGFloat dayCY = CGRectGetMaxY(timeview.frame)+5;
    CGFloat dayCW = 80;
    CGFloat dayCH = 40;
    UILabel *dayC = [[UILabel alloc]initWithFrame:CGRectMake(dayCX, dayCY, dayCW, dayCH)];
    dayC.text = @"4~7";
    dayC.textColor = [UIColor getColorWithHexNumber:@"FE93A2"];
    [self.view addSubview:dayC];
    
    
    CGFloat hLblX = HJDWidth - HJDHorizontalMargin *2;
    CGFloat hLblY = dayY;
    CGFloat hLblW = 40;
    CGFloat hLblH = dayH;
    UILabel *hLbl = [[UILabel alloc]initWithFrame:CGRectMake(hLblX, hLblY, hLblW, hLblH)];
    hLbl.text = @"天";
    [self.view addSubview:hLbl];
    
    //    横线
    CGFloat viewX = 0 ;
    CGFloat viewY = CGRectGetMaxY(dayLbl.frame);
    CGFloat viewW = HJDWidth ;
    CGFloat viewH = 1;
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(viewX, viewY, viewW, viewH)];
    view.backgroundColor = [UIColor getColorWithHexNumber:@"CFCFCF"];
    [self.view addSubview:view];
    
    CGFloat massX = HJDHorizontalMargin/2 ;
    CGFloat massY = CGRectGetMaxY(view.frame)+5;
    CGFloat massW = 80;
    CGFloat massH = 40;

    UILabel *masstextLbl = [[UILabel alloc]initWithFrame:CGRectMake(massX, massY,massW, massH )];
    masstextLbl.text = @"经期周期";
    masstextLbl.textColor = [UIColor getColorWithHexNumber:@"323232"];
    
    [self.view addSubview:masstextLbl];
    
    CGFloat weekCX = HJDWidth - 100 ;
    CGFloat weekCY = CGRectGetMaxY(view.frame)+5;
    CGFloat weekCW = 80;
    CGFloat weekCH = 40;
    UILabel *weekC = [[UILabel alloc]initWithFrame:CGRectMake(weekCX, weekCY, weekCW, weekCH)];
    weekC.text = @"28~30";
    weekC.textColor = [UIColor getColorWithHexNumber:@"FE93A2"];
    [self.view addSubview:weekC];
    
    CGFloat mLblX = HJDWidth - HJDHorizontalMargin *2 ;
    CGFloat mLblY = massY;
    CGFloat mLblW = 40;
    CGFloat mLblH = massH;
    UILabel *mLbl = [[UILabel alloc]initWithFrame:CGRectMake(mLblX, mLblY, mLblW, mLblH)];
    mLbl.text = @"天";
    [self.view addSubview:mLbl];
    //    横线
    CGFloat nowmassviewX = 0;
    CGFloat nowmassviewY = CGRectGetMaxY(masstextLbl.frame);
    CGFloat nowmassviewW = HJDWidth ;
    CGFloat nowmassviewH = 1;
    UIView *nowmassview = [[UIView alloc]initWithFrame:CGRectMake(nowmassviewX, nowmassviewY, nowmassviewW, nowmassviewH)];
    nowmassview.backgroundColor = [UIColor getColorWithHexNumber:@"CFCFCF"];
    [self.view addSubview:nowmassview];
    
    NSUserDefaults *defaD = [NSUserDefaults standardUserDefaults];
    NSString *preD = [defaD objectForKey:@"pregnanc"];

    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [inputFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *inputDate = [inputFormatter dateFromString:preD];
    NSDate *nextDate = [NSDate dateWithTimeInterval:24*60*60 * 280 sinceDate:inputDate];

//    NSLog(@"%@------%@",inputDate,nextDate);
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *strDate = [dateFormatter stringFromDate:nextDate];
//    NSLog(@"%@", strDate);
   
    
    
    UILabel *Ylbl = [[UILabel alloc]initWithFrame:CGRectMake((HJDWidth-60)/2-60, CGRectGetMaxY(nowmassview.frame)+ HJDVerticalMargin * 2,60 , 80)];
    Ylbl.textColor = [UIColor getColorWithHexNumber:@"FE93A2"];
    Ylbl.textAlignment = NSTextAlignmentCenter;
    Ylbl.text = @"预产期";
    Ylbl.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:Ylbl];
    
//    预产期
   self.lblTime = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(Ylbl.frame), CGRectGetMaxY(nowmassview.frame)+ HJDVerticalMargin * 2, 120, 80)];
    self.lblTime.textAlignment = NSTextAlignmentCenter;
    self.lblTime.text = strDate;
//    self.lblTime.text = [NSString stringWithFormat:@"%@",strDate];
    self.lblTime.textColor = [UIColor getColorWithHexNumber:@"FE93A2"];
    self.lblTime.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:self.lblTime];
}

//选择时间
-(void)timeBtnClick
{
    self.navigationController.navigationBarHidden = YES;
    [self setupDateView:DateTypeOfStart];
//    [self setupDateView:DateTypeOfEnd];
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    self.cal=[NSCalendar currentCalendar];
    _flags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday |
    NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    self.date = [formatter stringFromDate:[NSDate date]];
    
}

- (void)setupDateView:(DateType)type {
    
    
        _pickerView = [HJDDatePickerView instanceDatePickerView];
        _pickerView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
        [_pickerView setBackgroundColor:[UIColor greenColor]];
        _pickerView.delegate = self;
        _pickerView.type = type;
        [self.view addSubview:_pickerView];
    
   
    
}



- (void)getSelectDate:(NSString *)date type:(DateType)type {

    self.timeLbl.textColor = [UIColor getColorWithHexNumber:@"FE93A2"];
    
    switch (type) {
        case DateTypeOfStart:
            // TODO 日期确定选择
            self.navigationController.navigationBarHidden = NO;
            break;
            
        case DateTypeOfEnd:
            // TODO 日期取消选择
            self.navigationController.navigationBarHidden = NO;
//            NSLog(@"日期取消");
            break;
//        default:
//            break;
    }
    NSDate *lastDay = [NSDate dateWithTimeInterval:-24*60*60*14 sinceDate:[NSDate date]];//前7天
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *strDate = [dateFormatter stringFromDate:lastDay];

    int ci;
    NSComparisonResult result = [strDate compare:date];
    switch (result)
    {
            //date比self.date大
        case NSOrderedAscending:
             [MBProgressHUD showError:@"时间太早 可以选择14天以前的哦"];
           
            ci=1; break;
            //date比self.date小
        case NSOrderedDescending:
//            self.timeLbl.text = date;
//            ci=-1; break;
            //date=self.date
        case NSOrderedSame:
            self.timeLbl.text = date;
             self.timeLbl.textColor = [UIColor getColorWithHexNumber:@"FE93A2"];
            
            NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
            [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
            [inputFormatter setDateFormat:@"yyyy-MM-dd"];
            NSDate *inputDate = [inputFormatter dateFromString:date];
            NSDate *nextDate = [NSDate dateWithTimeInterval:24*60*60 * 280 sinceDate:inputDate];
            
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyy-MM-dd"];
            NSString *strDate = [dateFormatter stringFromDate:nextDate];
            
            self.lblTime.text = [NSString stringWithFormat:@"%@",strDate];
            ci=0; break;

    }

    
    
    
    
}


-(void)saveTimeBtnClick{
    NSString *url = @"/app/modifyUser.do";
    NSString *path = [Hurl stringByAppendingString:url];
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSUserDefaults *defaT = [NSUserDefaults standardUserDefaults];
    NSString *phone = [defaT objectForKey:@"phonenum"];
        NSString *pregnancy = [defaT objectForKey:@"pregnanc"];
    
        NSString *nickname = [defaT objectForKey:@"changNick"];
        NSData *qqDa = [[NSUserDefaults standardUserDefaults]valueForKey:@"qqD"];
        NSString *qq = [NSKeyedUnarchiver unarchiveObjectWithData:qqDa];
    
        NSData *nameDa = [[NSUserDefaults standardUserDefaults]valueForKey:@"nameD"];
        NSString *name = [NSKeyedUnarchiver unarchiveObjectWithData:nameDa];
        params[@"phone"] = phone;
        params[@"nickName"] = nickname;
        params[@"name"] = name;
        params[@"qq"] = qq;
        params[@"pregnancy"] = pregnancy;
        params[@"dueDate"] = self.lblTime.text;
    
        [mgr POST:path parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
    
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
            NSUserDefaults *defa = [NSUserDefaults standardUserDefaults];
            [defa setObject:self.timeLbl.text forKey:@"pregnanc"];
            [defa synchronize];
            
//            NSString *str = [ substringFromIndex:3];
//            NSLog(@"str==%@",str);
            NSData *dueDate = [NSKeyedArchiver archivedDataWithRootObject:self.lblTime.text];
            [[NSUserDefaults standardUserDefaults]setValue:dueDate forKey:@"due"];
    
            [self.navigationController popViewControllerAnimated:YES];
    
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [MBProgressHUD showError:@"服务器升级，请稍后再试"];
        }];


}



@end
